<template>
    <form class="validate-form-container">
        <slot name="default"></slot>
        <div class="submit-area" @click.prevent="submitForm">
            <slot name="submit">
                <button type="submit" class="btn btn-primary">提交</button>
            </slot>
        </div>
    </form>
</template>
<script lang="ts">
import {defineComponent, onUnmounted} from 'vue'
import bus from '../bus'
type ValidateFunc = () => boolean
export default defineComponent({
    name:'ValidateForm',
    // 定义触发事件
    emits:['form-submit'],
    setup(props,context){
        let funcArr: ValidateFunc[] = []
        const submitForm=()=>{
            // every:检测每一项都是真，才真，否则就是假
            // some:检测某一项是真，则真
            const result=funcArr.map(func=>func()).every(result=>result)
            // 触发父级组件的方法，并传值了
            context.emit('form-submit',result)
        }
        const callback = (func?: ValidateFunc) => {
            console.log('func',func)
            if (func) {
                funcArr.push(func)
            }
        }
        bus.$on('form-item-created', callback)
        onUnmounted(()=>{
            // bus.off('form-item-created',callback)
            funcArr=[]
        })
        return {
            submitForm
        }
    }
})
// 思路:  input子组件传过来函数，放在一个数组，用every,获取是否通过的结果，传给login页面(context.emit)
</script>